package team.yidong.fenda.wx.Service.Impl;

import com.qiniu.util.Json;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import team.yidong.fenda.entity.*;
import team.yidong.fenda.repository.*;
import team.yidong.fenda.utils.QiNiuYunUtil;
import team.yidong.fenda.wx.Service.WxQuestionService;

import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xuanlong on 2017/10/12.
 */
@Service
public class WxQuestionServiceImpl implements WxQuestionService {
    @Autowired
    AnswerRepository answerRepository;
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    QuestionURLRepository questionURLRepository;
    @Autowired
    MasterRepository masterRepository;
    @Autowired
    WxOrderRepository wxOrderRepository;

    @Override
    public JSONArray findWxQustion(Integer id, Integer page, Integer page_size) {
        int i;
        Pageable pageable = new PageRequest(page, page_size, Sort.Direction.DESC, "creatDate");
        List<Question> questionList = questionRepository.findByHospital(id, pageable);
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        JSONArray j = JSONArray.fromObject(questionList, config);
        return j;
    }

    @Transactional
    @Override
    public JSONObject findQuestionByIdOrUuName(Integer id, String uuId, String useruuid) {
        Question question = new Question();
        if (id != null) {
            question = questionRepository.findOne(id);
        } else if (uuId != null && !uuId.equals("")) {
            question = questionRepository.findByUuName(uuId);

        }
        if (useruuid != null && !useruuid.equals("")) {
            List<Answer> answerList = question.getAnswerList();
            for (Answer answer : answerList) {
                answer.setIsRead("1");
            }

            answerRepository.save(answerList);
        }
        question.getAnswerList();
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        JSONObject jb = JSONObject.fromObject(question, config);
        if (jb.getString("isAnonymous").equals("false")) {
            jb.put("isAnonymous", question.getUser().getName());
        }
        Integer questionId = Integer.parseInt(jb.getString("id"));

        JSONArray jsonArray = JSONArray.fromObject(questionURLRepository.findQuestionUrl(questionId), config);
        JSONArray jsonArray1 = new JSONArray();
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonArray1.element(jsonArray.getJSONObject(i).get("imgURL"));

            }
            jb.put("questionImgUrl", jsonArray1);
        }

        return jb;
    }

    @Override
    public JSONArray findQuestionByClass(Integer id, Integer page, Integer page_size, String questionClass) {
        Pageable pageable = new PageRequest(page, page_size, Sort.Direction.DESC, "id");
        List<Question> questionList = questionRepository.findByQuestionClass(id, questionClass, pageable);
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        return JSONArray.fromObject(questionList, config);
    }

    @Override
    public JSONArray findQuestionByUser(String wxNumber) {
        List<Question> questionList = questionRepository.findByUser(wxNumber);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        return JSONArray.fromObject(questionList, jsonConfig);

    }

    @Transactional
    @Override
    public String addQuestion(String wxNumber, String info, String createDate, String imgUrl, String questionClass, Integer isOneMaster, Double timeNum, String headImg, String nickName, String isAnonymous, Double askMoney, String out_trade_no) {
        User user = userRepository.findByUserOpenId(wxNumber);
        user.setHeadImg(headImg);
        user.setName(nickName);
        userRepository.saveAndFlush(user);
        Question question = new Question();
        question.setUser(user);
        if (isAnonymous.equals("false")) {
            question.setIsAnonymous(nickName);
        } else {
            question.setIsAnonymous("true");
        }

        if (out_trade_no != null && !out_trade_no.equals("")) {

            WxOrder wxOrder = new WxOrder();
            wxOrder.setOutTradeNo(out_trade_no);
            wxOrder.setOrderQuestion(question);
            wxOrder.setStatus("notStart");
            wxOrder.setOrderQuestion(question);
            wxOrderRepository.save(wxOrder);
        } else {
            WxOrder wxOrder = new WxOrder();
            wxOrder.setMoney(0);
            wxOrder.setStatus("finish");
            wxOrder.setHandleStatus("免费");
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String endDate = simpleDateFormat.format(date);
            wxOrder.setTimeEnd(endDate);
            wxOrder.setOrderQuestion(question);
            wxOrderRepository.save(wxOrder);
        }
        question.setAnswerStatus("可回答");
        question.setInfo(info);
        question.setStatus("white");
        question.setTimeNum(timeNum);
        question.setIsSolved("否");
        createDate = createDate.replace("/", "-");
        question.setCreatDate(createDate);
        question.setIsOneMaster(isOneMaster);
        if (isOneMaster == 0) {
            question.setQuestionClass(questionClass);
        } else {
            question.setQuestionClass("特问");
        }

        String uuName = UUID.randomUUID().toString().replace("-", "");
        question.setUuName(uuName);

        if (imgUrl != null && !imgUrl.equals("")) {
            JSONArray jsonArray = JSONArray.fromObject(imgUrl);
            for (int i = 0; i < jsonArray.size(); i++) {
                String str = (String) jsonArray.get(i);
                str = str.replace("wxfile:", "https://");
                str = str.substring(0, 8) + "qny.liuxuanlong.xyz/" + str.substring(8);
                QuestionURL questionURL = new QuestionURL();
                questionURL.setImgURL(str);
                questionURL.setQuestion(question);
                questionURLRepository.save(questionURL);

            }
        }


        questionRepository.save(question);
        return uuName;
    }

    @Override
    public Question findOne(Integer questionId) {
        return questionRepository.findOne(questionId);
    }

    //没有回答过的特问的问题
    @Override
    public JSONArray findQuestionByMaster(String openId) {
        Integer masterId = masterRepository.findByOpenId(openId).getId();
        List<Question> questionList = questionRepository.findAllQuestionByAnswerMaster(openId);
        Pageable pageable = new PageRequest(0, 10, Sort.Direction.DESC, "creatDate");
        Page<Question> questionPage = questionRepository.findAll(new Specification<Question>() {
            @Override
            public Predicate toPredicate(Root<Question> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
/*                Join<Question, Answer> join1 = root.join("answerList");
                Join<Join, Master> join2 = join1.join("master");*/

                //not in
                if (questionList.size() != 0) {

                    Predicate p1 = root.in(questionList).not();
                    predicateList.add(p1);
                }
                Predicate p1 = criteriaBuilder.notEqual(root.get("status").as(String.class), "black");
                predicateList.add(p1);
                Predicate p2 = criteriaBuilder.equal(root.get("isOneMaster"), masterId);
                predicateList.add(p2);
/*                Predicate p4 = criteriaBuilder.equal(root.get("questionClass"), questionClass);
                predicateList.add(p4);*/
                Predicate p5 = criteriaBuilder.equal(root.get("answerStatus"), "可回答");
                predicateList.add(p5);

                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, pageable);

        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        JSONObject jsonObject = JSONObject.fromObject(questionPage, config);
        JSONArray jsonArray = jsonObject.getJSONArray("content");
        return jsonArray;
    }

    @Override
    public JSONArray findQuestionByAnswerMaster(String openId) {


        List<Question> questionList = questionRepository.findQuestionByAnswerMaster(openId);

        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        JSONArray jsonArray = JSONArray.fromObject(questionList, config);
        return jsonArray;

    }

    //没有回答过的非特问的问题
    @Override
    public JSONArray findByNotAnswerANdQuestionClass(String openId, String questionClass, String kind, Integer page, Integer page_size) {


        if ("全部".equals(kind) || "按时间".equals(kind)) {
            Pageable pageable = new PageRequest(page, page_size, Sort.Direction.ASC, "creatDate");
            Page<Question> questionPage = questionRepository.findAll(new Specification<Question>() {
                @Override
                public Predicate toPredicate(Root<Question> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicateList = new ArrayList<>();


                    //not in
                    List<Question> questionList = questionRepository.findAllQuestionByAnswerMaster(openId);
                    if (questionList.size() != 0) {

                        Predicate p1 = root.in(questionList).not();
                        predicateList.add(p1);
                    }
                    Predicate p1 = criteriaBuilder.notEqual(root.get("status").as(String.class), "black");
                    predicateList.add(p1);
                    Predicate p2 = criteriaBuilder.equal(root.get("isOneMaster"), 0);
                    predicateList.add(p2);
                    Predicate p4 = criteriaBuilder.equal(root.get("questionClass"), questionClass);
                    predicateList.add(p4);
                    Predicate p5 = criteriaBuilder.equal(root.get("answerStatus"), "可回答");
                    predicateList.add(p5);
                    criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                    return null;
                }
            }, pageable);

            JsonConfig config = new JsonConfig();
            config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
            JSONObject jsonObject = JSONObject.fromObject(questionPage, config);
            JSONArray jsonArray = jsonObject.getJSONArray("content");
            return jsonArray;
        } else {
            Pageable pageable = new PageRequest(page, page_size);
            Page<Question> questionPage = answerRepository.findQuestionOrderByAnswerNum(openId, questionClass, pageable);
            JsonConfig config = new JsonConfig();
            config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
            JSONObject jsonObject = JSONObject.fromObject(questionPage, config);
            JSONArray jsonArray = jsonObject.getJSONArray("content");
            return jsonArray;
        }

    }

    @Override
    public JSONArray findTewenQuestion(String openid) {
        List<Question> questionList = questionRepository.findTewenQuestion(openid);

        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "masterScoreSet", "question", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", " masterScore", "orderMoneyToList", "orderQuestion", "masterAnswerList"});
        JSONArray jsonArray = JSONArray.fromObject(questionList, config);
        return jsonArray;
    }


}
